#include <string>
#include "search.h"
#include "Types.h"
#include "movegen.h"
using namespace std;

namespace Search {

  volatile SignalsType Signals;
  LimitsType Limits;
  std::vector<RootMove> RootMoves;
  Position RootPosition;
  //Time SearchTime;
}

namespace {

  // Set to true to force running with one thread. Used for debugging
  const bool FakeSplit = false;

  // Different node types, used as template parameter
  enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };

  // Lookup table to check if a Piece is a slider and its access function
  const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
  inline bool piece_is_slider(Piece p) { return Slidings[p]; }

  // Maximum depth for razoring
  const Depth RazorDepth = 4 * ONE_PLY;

  // Dynamic razoring margin based on depth
  inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }

  // Maximum depth for use of dynamic threat detection when null move fails low
  const Depth ThreatDepth = 5 * ONE_PLY;

  // Minimum depth for use of internal iterative deepening
  const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };

  // At Non-PV nodes we do an internal iterative deepening search
  // when the static evaluation is bigger then beta - IIDMargin.
  const Value IIDMargin = Value(0x100);

  // Minimum depth for use of singular extension
  const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };

  // Futility margin for quiescence search
  const Value FutilityMarginQS = Value(0x80);

  // Futility lookup tables (initialized at startup) and their access functions
  Value FutilityMargins[16][64]; // [depth][moveNumber]
  int FutilityMoveCounts[32];    // [depth]

  inline Value futility_margin(Depth d, int mn) {

    return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
                           : 2 * VALUE_INFINITE;
  }

  inline int futility_move_count(Depth d) {

    return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
  }

  // Reduction lookup tables (initialized at startup) and their access function
  int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]

  template <bool PvNode> inline Depth reduction(Depth d, int mn) {

    return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
  }

  // Easy move margin. An easy move candidate must be at least this much better
  // than the second best move.
  const Value EasyMoveMargin = Value(0x150);

  // This is the minimum interval in msec between two check_time() calls
  const int TimerResolution = 5;


  size_t MultiPV, UCIMultiPV, PVIdx;
//  TimeManager TimeMgr;
  int BestMoveChanges;
  int SkillLevel;
  bool SkillLevelEnabled, Chess960;
  //History H;


  //template <NodeType NT> Value search(Position& pos, /*Stack* ss,*/ Value alpha, Value beta, Depth depth);

  template <NodeType NT>
  Value qsearch(Position& pos, /*Stack* ss,*/ Value alpha, Value beta, Depth depth);

  void id_loop(Position& pos);
  //bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
  //bool connected_moves(const Position& pos, Move m1, Move m2);
  Value value_to_tt(Value v, int ply);
  Value value_from_tt(Value v, int ply);
  //bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
  //bool connected_threat(const Position& pos, Move m, Move threat);
  //Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
  //Move do_skill_level();
  string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
  void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
  //void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);

  // MovePickerExt class template extends MovePicker and allows to choose at
  // compile time the proper moves source according to the type of node. In the
  // default case we simply create and use a standard MovePicker object.
 /*
  template<bool SpNode> struct MovePickerExt : public MovePicker {

    MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
                  : MovePicker(p, ttm, d, h, ss, b) {}
  };
  */

  /*
  // In case of a SpNode we use split point's shared MovePicker object as moves source
  template<> struct MovePickerExt<true> : public MovePicker {

    MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
                  : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}

    Move next_move() { return mp->next_move(); }
    MovePicker* mp;
  };
  */

  /*
  // is_dangerous() checks whether a move belongs to some classes of known
  // 'dangerous' moves so that we avoid to prune it.
  FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {

    // Test for a pawn pushed to 7th or a passed pawn move
    if (type_of(pos.piece_moved(m)) == PAWN)
    {
        Color c = pos.side_to_move();
        if (   relative_rank(c, to_sq(m)) == RANK_7
            || pos.pawn_is_passed(c, to_sq(m)))
            return true;
    }
	

    // Test for a capture that triggers a pawn endgame
    if (   captureOrPromotion
        && type_of(pos.piece_on(to_sq(m))) != PAWN
        && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
            - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO)
        && !is_special(m))
        return true;

    return false;
  }
*/

} // namespace

using namespace Search;


/// Search::think() is the external interface to Stockfish's search, and is
/// called by the main thread when the program receives the UCI 'go' command. It
/// searches from RootPosition and at the end prints the "bestmove" to output.
/*
void think() {

  //static Book book; // Defined static to initialize the PRNG only once

  Position& pos = RootPosition;
  Chess960 = pos.is_chess960();
  Eval::RootColor = pos.side_to_move();
  TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
  TT.new_search();
  H.clear();

  if (RootMoves.empty())
  {
      cout << "info depth 0 score "
           << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;

      RootMoves.push_back(MOVE_NONE);
      goto finalize;
  }

  if (Options["OwnBook"] && !Limits.infinite)
  {
      Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);

      if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
      {
          std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
          goto finalize;
      }
  }

  UCIMultiPV = Options["MultiPV"];
  SkillLevel = Options["Skill Level"];

  // Do we have to play with skill handicap? In this case enable MultiPV that
  // we will use behind the scenes to retrieve a set of possible moves.
  SkillLevelEnabled = (SkillLevel < 20);
  MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);

  if (Options["Use Search Log"])
  {
      Log log(Options["Search Log Filename"]);
      log << "\nSearching: "  << pos.to_fen()
          << "\ninfinite: "   << Limits.infinite
          << " ponder: "      << Limits.ponder
          << " time: "        << Limits.time[pos.side_to_move()]
          << " increment: "   << Limits.inc[pos.side_to_move()]
          << " moves to go: " << Limits.movestogo
          << endl;
  }

  Threads.wake_up();

  // Set best timer interval to avoid lagging under time pressure. Timer is
  // used to check for remaining available thinking time.
  if (Limits.use_time_management())
      Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
  else
      Threads.set_timer(100);

  // We're ready to start searching. Call the iterative deepening loop function
  id_loop(pos);

  Threads.set_timer(0); // Stop timer
  Threads.sleep();

  if (Options["Use Search Log"])
  {
      int e = SearchTime.elapsed();

      Log log(Options["Search Log Filename"]);
      log << "Nodes: "          << pos.nodes_searched()
          << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
          << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);

      StateInfo st;
      pos.do_move(RootMoves[0].pv[0], st);
      log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
      pos.undo_move(RootMoves[0].pv[0]);
  }

finalize:

  // When we reach max depth we arrive here even without Signals.stop is raised,
  // but if we are pondering or in infinite search, we shouldn't print the best
  // move before we are told to do so.
  if (!Signals.stop && (Limits.ponder || Limits.infinite))
      pos.this_thread()->wait_for_stop_or_ponderhit();

  // Best move could be MOVE_NONE when searching on a stalemate position
  cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
       << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
}

*/






  // id_loop() is the main iterative deepening loop. It calls search() repeatedly
  // with increasing depth until the allocated thinking time has been consumed,
  // user stops the search, or the maximum search depth is reached.

  void id_loop(Position& pos) {

	 
    //Stack ss[MAX_PLY_PLUS_2];
    int depth;
	//int prevBestMoveChanges;
    Value bestValue, alpha, beta, delta;
    bool bestMoveNeverChanged = true;
    //Move skillBest = MOVE_NONE;

    //memset(ss, 0, 4 * sizeof(Stack));
    //depth = BestMoveChanges = 0;
    depth = 0;
	bestValue = delta = -VALUE_INFINITE;
    //ss->currentMove = MOVE_NULL; // Hack to skip update gains
	

    // Iterative deepening loop until requested to stop or target depth reached
    while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
    //while( (ChessEngine.brainStatus == THINKING) && (depth <= ChessEngine.maxDepth))
	{
        // Save last iteration's scores before first PV line is searched and all
        // the move scores but the (new) PV are set to -VALUE_INFINITE.
        for (size_t i = 0; i < RootMoves.size(); i++)
            RootMoves[i].prevScore = RootMoves[i].score;

        //prevBestMoveChanges = BestMoveChanges;
        //BestMoveChanges = 0;

        // MultiPV loop. We perform a full root search for each PV line /// <--- late dev option
        //for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
        //{
			/*
            // Set aspiration window default width
            if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
            {
                delta = Value(16);
                alpha = RootMoves[PVIdx].prevScore - delta;
                beta  = RootMoves[PVIdx].prevScore + delta;
            }
            else
            {*/
                alpha = -VALUE_INFINITE;
                beta  =  VALUE_INFINITE;
            //}

				//******* <-- end dev
            // Start with a small aspiration window and, in case of fail high/low,
            // research with bigger window until not failing high/low anymore.
            //do {
                // Search starts from ss+1 to allow referencing (ss-1). This is
                // needed by update gains and ss copy when splitting at Root.
                //bestValue = search<Root>(pos, /*ss+1,*/ alpha, beta, depth * ONE_PLY);

                // Bring to front the best move. It is critical that sorting is
                // done with a stable algorithm because all the values but the first
                // and eventually the new best one are set to -VALUE_INFINITE and
                // we want to keep the same order for all the moves but the new
                // PV that goes to the front. Note that in case of MultiPV search
                // the already searched PV lines are preserved.
                sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());

                // In case we have found an exact score and we are going to leave
                // the fail high/low loop then reorder the PV moves, otherwise
                // leave the last PV move in its position so to be searched again.
                // Of course this is needed only in MultiPV search.
                if (PVIdx && bestValue > alpha && bestValue < beta)
                    sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);

				/*
				// <--- late dev option
                // Write PV back to transposition table in case the relevant
                // entries have been overwritten during the search.
                for (size_t i = 0; i <= PVIdx; i++)
                    RootMoves[i].insert_pv_in_tt(pos);
					*/

                // If search has been stopped exit the aspiration window loop.
                // Sorting and writing PV back to TT is safe becuase RootMoves
                // is still valid, although refers to previous iteration.
                if (Signals.stop)
                    break;

                // Send full PV info to GUI if we are going to leave the loop or
                // if we have a fail high/low and we are deep in the search.
				// TODO: translate this condition
                // TODO: reimplement this
				/*
				if ((bestValue > alpha && bestValue < beta) || SearchTime.elapsed() > 2000)
                    pv_info_to_uci(pos, depth, alpha, beta);
				*/

				//******** end dev
				/*
                // In case of failing high/low increase aspiration window and
                // research, otherwise exit the fail high/low loop.
                if (bestValue >= beta)
                {
                    beta += delta;
                    delta += delta / 2;
                }
                else if (bestValue <= alpha)
                {
                    Signals.failedLowAtRoot = true;
                    Signals.stopOnPonderhit = false;

                    alpha -= delta;
                    delta += delta / 2;
                }
                else
                    break;

                assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
				*/

            //} while (abs(bestValue) < VALUE_KNOWN_WIN);
        //}

		/*
        // Skills: Do we need to pick now the best move ?
        if (SkillLevelEnabled && depth == 1 + SkillLevel)
            skillBest = do_skill_level();
			*/

		/*
        if (!Signals.stop && Options["Use Search Log"])
             pv_info_to_log(pos, depth, bestValue, SearchTime.elapsed(), &RootMoves[0].pv[0]);
			 */

			/*
        // Filter out startup noise when monitoring best move stability
        if (depth > 2 && BestMoveChanges)
            bestMoveNeverChanged = false;
			*/

        // Do we have time for the next iteration? Can we stop searching now?
        if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
        {
            bool stop = false; // Local variable, not the volatile Signals.stop

			/*
            // Take in account some extra time if the best move has changed
            if (depth > 4 && depth < 50)
                TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
				*/

			/***** 
            // Stop search if most of available time is already consumed. We
            // probably don't have enough time to search the first move at the
            // next iteration anyway.
            if (SearchTime.elapsed() > (TimeMgr.available_time() * 62) / 100)
                stop = true;
				*/


			/*
            // Stop search early if one move seems to be much better than others
            if (    depth >= 12
                && !stop
                && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
                    || SearchTime.elapsed() > (TimeMgr.available_time() * 40) / 100))
            {
                Value rBeta = bestValue - EasyMoveMargin;
                (ss+1)->excludedMove = RootMoves[0].pv[0];
                (ss+1)->skipNullMove = true;
                Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
                (ss+1)->skipNullMove = false;
                (ss+1)->excludedMove = MOVE_NONE;

                if (v < rBeta)
                    stop = true;
            }
			*/

            if (stop)
            {
                // If we are allowed to ponder do not stop the search now but
                // keep pondering until GUI sends "ponderhit" or "stop".
                if (Limits.ponder)
                    Signals.stopOnPonderhit = true;
                else
                    Signals.stop = true;
            }
        }
    }

	/*
    // When using skills swap best PV line with the sub-optimal one
    if (SkillLevelEnabled)
    {
        if (skillBest == MOVE_NONE) // Still unassigned ?
            skillBest = do_skill_level();

        std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
    }*/
  }





    // search<>() is the main search function for both PV and non-PV nodes and for
  // normal and SplitPoint nodes. When called just after a split point the search
  // is simpler because we have already probed the hash table, done a null move
  // search, and searched the first move before splitting, we don't have to repeat
  // all this work again. We also don't need to store anything to the hash table
  // here: This is taken care of after we return from the split point.
  /*
  template <NodeType NT>
  Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {

    const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
    const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
    const bool RootNode = (NT == Root || NT == SplitPointRoot);

    assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
    assert((alpha == beta - 1) || PvNode);
    assert(depth > DEPTH_ZERO);

    Move movesSearched[64];
    StateInfo st;
    const TTEntry *tte;
    Key posKey;
    Move ttMove, move, excludedMove, bestMove, threatMove;
    Depth ext, newDepth;
    Bound bt;
    Value bestValue, value, oldAlpha, ttValue;
    Value refinedValue, nullValue, futilityBase, futilityValue;
    bool isPvMove, inCheck, singularExtensionNode, givesCheck;
    bool captureOrPromotion, dangerous, doFullDepthSearch;
    int moveCount = 0, playedMoveCount = 0;
    Thread* thisThread = pos.this_thread();
    SplitPoint* sp = NULL;

    refinedValue = bestValue = value = -VALUE_INFINITE;
    oldAlpha = alpha;
    inCheck = pos.in_check();
    ss->ply = (ss-1)->ply + 1;

	/*

    // Used to send selDepth info to GUI
    if (PvNode && thisThread->maxPly < ss->ply)
        thisThread->maxPly = ss->ply;

    // Step 1. Initialize node
    if (SpNode)
    {
        tte = NULL;
        ttMove = excludedMove = MOVE_NONE;
        ttValue = VALUE_ZERO;
        sp = ss->sp;
        bestMove = sp->bestMove;
        threatMove = sp->threatMove;
        bestValue = sp->bestValue;
        moveCount = sp->moveCount; // Lock must be held here

        assert(bestValue > -VALUE_INFINITE && moveCount > 0);

        goto split_point_start;
    }
    else
    {
        ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
        (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
        (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;

    }

    // Step 2. Check for aborted search and immediate draw
    // Enforce node limit here. FIXME: This only works with 1 search thread.
    if (Limits.nodes && pos.nodes_searched() >= Limits.nodes)
        Signals.stop = true;

    if ((   Signals.stop
         || pos.is_draw<false>()
         || ss->ply > MAX_PLY) && !RootNode)
        return VALUE_DRAW;

    // Step 3. Mate distance pruning. Even if we mate at the next move our score
    // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
    // a shorter mate was found upward in the tree then there is no need to search
    // further, we will never beat current alpha. Same logic but with reversed signs
    // applies also in the opposite condition of being mated instead of giving mate,
    // in this case return a fail-high score.
    if (!RootNode)
    {
        alpha = std::max(mated_in(ss->ply), alpha);
        beta = std::min(mate_in(ss->ply+1), beta);
        if (alpha >= beta)
            return alpha;
    }

    // Step 4. Transposition table lookup
    // We don't want the score of a partial search to overwrite a previous full search
    // TT value, so we use a different position key in case of an excluded move.
    excludedMove = ss->excludedMove;
    posKey = excludedMove ? pos.exclusion_key() : pos.key();
    tte = TT.probe(posKey);
    ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
    ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_ZERO;

    // At PV nodes we check for exact scores, while at non-PV nodes we check for
    // a fail high/low. Biggest advantage at probing at PV nodes is to have a
    // smooth experience in analysis mode. We don't probe at Root nodes otherwise
    // we should also update RootMoveList to avoid bogus output.
    if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
                                    : can_return_tt(tte, depth, ttValue, beta)))
    {
        TT.refresh(tte);
        ss->currentMove = ttMove; // Can be MOVE_NONE

        if (   ttValue >= beta
            && ttMove
            && !pos.is_capture_or_promotion(ttMove)
            && ttMove != ss->killers[0])
        {
            ss->killers[1] = ss->killers[0];
            ss->killers[0] = ttMove;
        }
        return ttValue;
    }

    // Step 5. Evaluate the position statically and update parent's gain statistics
    if (inCheck)
        ss->eval = ss->evalMargin = VALUE_NONE;
    else if (tte)
    {
        assert(tte->static_value() != VALUE_NONE);

        ss->eval = tte->static_value();
        ss->evalMargin = tte->static_value_margin();
        refinedValue = refine_eval(tte, ttValue, ss->eval);
    }
    else
    {
        refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
        TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
    }

    // Update gain for the parent non-capture move given the static position
    // evaluation before and after the move.
    if (   (move = (ss-1)->currentMove) != MOVE_NULL
        && (ss-1)->eval != VALUE_NONE
        && ss->eval != VALUE_NONE
        && !pos.captured_piece_type()
        && !is_special(move))
    {
        Square to = to_sq(move);
        H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
    }

    // Step 6. Razoring (is omitted in PV nodes)
    if (   !PvNode
        &&  depth < RazorDepth
        && !inCheck
        &&  refinedValue + razor_margin(depth) < beta
        &&  ttMove == MOVE_NONE
        &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
        && !pos.pawn_on_7th(pos.side_to_move()))
    {
        Value rbeta = beta - razor_margin(depth);
        Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
        if (v < rbeta)
            // Logically we should return (v + razor_margin(depth)), but
            // surprisingly this did slightly weaker in tests.
            return v;
    }

    // Step 7. Static null move pruning (is omitted in PV nodes)
    // We're betting that the opponent doesn't have a move that will reduce
    // the score by more than futility_margin(depth) if we do a null move.
    if (   !PvNode
        && !ss->skipNullMove
        &&  depth < RazorDepth
        && !inCheck
        &&  refinedValue - futility_margin(depth, 0) >= beta
        &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
        &&  pos.non_pawn_material(pos.side_to_move()))
        return refinedValue - futility_margin(depth, 0);

    // Step 8. Null move search with verification search (is omitted in PV nodes)
    if (   !PvNode
        && !ss->skipNullMove
        &&  depth > ONE_PLY
        && !inCheck
        &&  refinedValue >= beta
        &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
        &&  pos.non_pawn_material(pos.side_to_move()))
    {
        ss->currentMove = MOVE_NULL;

        // Null move dynamic reduction based on depth
        int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);

        // Null move dynamic reduction based on value
        if (refinedValue - PawnValueMidgame > beta)
            R++;

        pos.do_null_move<true>(st);
        (ss+1)->skipNullMove = true;
        nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
                                              : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
        (ss+1)->skipNullMove = false;
        pos.do_null_move<false>(st);

        if (nullValue >= beta)
        {
            // Do not return unproven mate scores
            if (nullValue >= VALUE_MATE_IN_MAX_PLY)
                nullValue = beta;

            if (depth < 6 * ONE_PLY)
                return nullValue;

            // Do verification search at high depths
            ss->skipNullMove = true;
            Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
            ss->skipNullMove = false;

            if (v >= beta)
                return nullValue;
        }
        else
        {
            // The null move failed low, which means that we may be faced with
            // some kind of threat. If the previous move was reduced, check if
            // the move that refuted the null move was somehow connected to the
            // move which was reduced. If a connection is found, return a fail
            // low score (which will cause the reduced move to fail high in the
            // parent node, which will trigger a re-search with full depth).
            threatMove = (ss+1)->currentMove;

            if (   depth < ThreatDepth
                && (ss-1)->reduction
                && threatMove != MOVE_NONE
                && connected_moves(pos, (ss-1)->currentMove, threatMove))
                return beta - 1;
        }
    }

    // Step 9. ProbCut (is omitted in PV nodes)
    // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
    // and a reduced search returns a value much above beta, we can (almost) safely
    // prune the previous move.
    if (   !PvNode
        &&  depth >= RazorDepth + ONE_PLY
        && !inCheck
        && !ss->skipNullMove
        &&  excludedMove == MOVE_NONE
        &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
    {
        Value rbeta = beta + 200;
        Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;

        assert(rdepth >= ONE_PLY);
        assert((ss-1)->currentMove != MOVE_NONE);
        assert((ss-1)->currentMove != MOVE_NULL);

        MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
        CheckInfo ci(pos);

        while ((move = mp.next_move()) != MOVE_NONE)
            if (pos.pl_move_is_legal(move, ci.pinned))
            {
                ss->currentMove = move;
                pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
                value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
                pos.undo_move(move);
                if (value >= rbeta)
                    return value;
            }
    }

    // Step 10. Internal iterative deepening
    if (   depth >= IIDDepth[PvNode]
        && ttMove == MOVE_NONE
        && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
    {
        Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);

        ss->skipNullMove = true;
        search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
        ss->skipNullMove = false;

        tte = TT.probe(posKey);
        ttMove = tte ? tte->move() : MOVE_NONE;
    }

split_point_start: // At split points actual search starts from here

    MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
    CheckInfo ci(pos);
    futilityBase = ss->eval + ss->evalMargin;
    singularExtensionNode =   !RootNode
                           && !SpNode
                           && depth >= SingularExtensionDepth[PvNode]
                           && ttMove != MOVE_NONE
                           && !excludedMove // Recursive singular search is not allowed
                           && (tte->type() & BOUND_LOWER)
                           && tte->depth() >= depth - 3 * ONE_PLY;

    // Step 11. Loop through moves
    // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
    while (   bestValue < beta
           && (move = mp.next_move()) != MOVE_NONE
           && !thisThread->cutoff_occurred()
           && !Signals.stop)
    {
      assert(is_ok(move));

      if (move == excludedMove)
          continue;

      // At root obey the "searchmoves" option and skip moves not listed in Root
      // Move List, as a consequence any illegal move is also skipped. In MultiPV
      // mode we also skip PV moves which have been already searched.
      if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
          continue;

      // At PV and SpNode nodes we want all moves to be legal since the beginning
      if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
          continue;

      if (SpNode)
      {
          moveCount = ++sp->moveCount;
          lock_release(sp->lock);
      }
      else
          moveCount++;

      if (RootNode)
      {
          Signals.firstRootMove = (moveCount == 1);

          if (thisThread == Threads.main_thread() && SearchTime.elapsed() > 2000)
              cout << "info depth " << depth / ONE_PLY
                   << " currmove " << move_to_uci(move, Chess960)
                   << " currmovenumber " << moveCount + PVIdx << endl;
      }

      isPvMove = (PvNode && moveCount <= 1);
      captureOrPromotion = pos.is_capture_or_promotion(move);
      givesCheck = pos.move_gives_check(move, ci);
      dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
      ext = DEPTH_ZERO;

      // Step 12. Extend checks and, in PV nodes, also dangerous moves
      if (PvNode && dangerous)
          ext = ONE_PLY;

      else if (givesCheck && pos.see_sign(move) >= 0)
          ext = PvNode ? ONE_PLY : ONE_PLY / 2;

      // Singular extension search. If all moves but one fail low on a search of
      // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
      // is singular and should be extended. To verify this we do a reduced search
      // on all the other moves but the ttMove, if result is lower than ttValue minus
      // a margin then we extend ttMove.
      if (   singularExtensionNode
          && !ext
          && move == ttMove
          && pos.pl_move_is_legal(move, ci.pinned))
      {
          if (abs(ttValue) < VALUE_KNOWN_WIN)
          {
              Value rBeta = ttValue - int(depth);
              ss->excludedMove = move;
              ss->skipNullMove = true;
              value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
              ss->skipNullMove = false;
              ss->excludedMove = MOVE_NONE;
              if (value < rBeta)
                  ext = ONE_PLY;
          }
      }

      // Update current move (this must be done after singular extension search)
      newDepth = depth - ONE_PLY + ext;

      // Step 13. Futility pruning (is omitted in PV nodes)
      if (   !PvNode
          && !captureOrPromotion
          && !inCheck
          && !dangerous
          &&  move != ttMove
          && !is_castle(move)
          && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
      {
          // Move count based pruning
          if (   moveCount >= futility_move_count(depth)
              && (!threatMove || !connected_threat(pos, move, threatMove)))
          {
              if (SpNode)
                  lock_grab(sp->lock);

              continue;
          }

          // Value based pruning
          // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
          // but fixing this made program slightly weaker.
          Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
          futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
                         + H.gain(pos.piece_moved(move), to_sq(move));

          if (futilityValue < beta)
          {
              if (SpNode)
                  lock_grab(sp->lock);

              continue;
          }

          // Prune moves with negative SEE at low depths
          if (   predictedDepth < 2 * ONE_PLY
              && pos.see_sign(move) < 0)
          {
              if (SpNode)
                  lock_grab(sp->lock);

              continue;
          }
      }

      // Check for legality only before to do the move
      if (!pos.pl_move_is_legal(move, ci.pinned))
      {
          moveCount--;
          continue;
      }

      ss->currentMove = move;
      if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
          movesSearched[playedMoveCount++] = move;

      // Step 14. Make the move
      pos.do_move(move, st, ci, givesCheck);

      // Step 15. Reduced depth search (LMR). If the move fails high will be
      // re-searched at full depth.
      if (   depth > 3 * ONE_PLY
          && !isPvMove
          && !captureOrPromotion
          && !dangerous
          && !is_castle(move)
          &&  ss->killers[0] != move
          &&  ss->killers[1] != move)
      {
          ss->reduction = reduction<PvNode>(depth, moveCount);
          Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
          alpha = SpNode ? sp->alpha : alpha;

          value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);

          doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
          ss->reduction = DEPTH_ZERO;
      }
      else
          doFullDepthSearch = !isPvMove;

      // Step 16. Full depth search, when LMR is skipped or fails high
      if (doFullDepthSearch)
      {
          alpha = SpNode ? sp->alpha : alpha;
          value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
                                     : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
      }

      // Only for PV nodes do a full PV search on the first move or after a fail
      // high, in the latter case search only if value < beta, otherwise let the
      // parent node to fail low with value <= alpha and to try another move.
      if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
          value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
                                     : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);

      // Step 17. Undo move
      pos.undo_move(move);

      assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);

      // Step 18. Check for new best move
      if (SpNode)
      {
          lock_grab(sp->lock);
          bestValue = sp->bestValue;
          alpha = sp->alpha;
      }

      // Finished searching the move. If Signals.stop is true, the search
      // was aborted because the user interrupted the search or because we
      // ran out of time. In this case, the return value of the search cannot
      // be trusted, and we don't update the best move and/or PV.
      if (RootNode && !Signals.stop)
      {
          RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);

          // PV move or new best move ?
          if (isPvMove || value > alpha)
          {
              rm.score = value;
              rm.extract_pv_from_tt(pos);

              // We record how often the best move has been changed in each
              // iteration. This information is used for time management: When
              // the best move changes frequently, we allocate some more time.
              if (!isPvMove && MultiPV == 1)
                  BestMoveChanges++;
          }
          else
              // All other moves but the PV are set to the lowest value, this
              // is not a problem when sorting becuase sort is stable and move
              // position in the list is preserved, just the PV is pushed up.
              rm.score = -VALUE_INFINITE;

      }

      if (value > bestValue)
      {
          bestValue = value;
          bestMove = move;

          if (   PvNode
              && value > alpha
              && value < beta) // We want always alpha < beta
              alpha = value;

          if (SpNode && !thisThread->cutoff_occurred())
          {
              sp->bestValue = value;
              sp->bestMove = move;
              sp->alpha = alpha;

              if (value >= beta)
                  sp->cutoff = true;
          }
      }

      // Step 19. Check for split
      if (   !SpNode
          && depth >= Threads.min_split_depth()
          && bestValue < beta
          && Threads.available_slave_exists(thisThread)
          && !Signals.stop
          && !thisThread->cutoff_occurred())
          bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
                                               depth, threatMove, moveCount, &mp, NT);
    }

    // Step 20. Check for mate and stalemate
    // All legal moves have been searched and if there are no legal moves, it
    // must be mate or stalemate. Note that we can have a false positive in
    // case of Signals.stop or thread.cutoff_occurred() are set, but this is
    // harmless because return value is discarded anyhow in the parent nodes.
    // If we are in a singular extension search then return a fail low score.
    if (!moveCount)
        return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;

    // If we have pruned all the moves without searching return a fail-low score
    if (bestValue == -VALUE_INFINITE)
    {
        assert(!playedMoveCount);

        bestValue = oldAlpha;
    }

    // Step 21. Update tables
    // Update transposition table entry, killers and history
    if (!SpNode && !Signals.stop && !thisThread->cutoff_occurred())
    {
        move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
        bt   = bestValue <= oldAlpha ? BOUND_UPPER
             : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;

        TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);

        // Update killers and history for non capture cut-off moves
        if (    bestValue >= beta
            && !pos.is_capture_or_promotion(move)
            && !inCheck)
        {
            if (move != ss->killers[0])
            {
                ss->killers[1] = ss->killers[0];
                ss->killers[0] = move;
            }

            // Increase history value of the cut-off move
            Value bonus = Value(int(depth) * int(depth));
            H.add(pos.piece_moved(move), to_sq(move), bonus);

            // Decrease history of all the other played non-capture moves
            for (int i = 0; i < playedMoveCount - 1; i++)
            {
                Move m = movesSearched[i];
                H.add(pos.piece_moved(m), to_sq(m), -bonus);
            }
        }
    }

    assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
	*//*
    return bestValue;
  }
  */

// full_search()

/*
//static int full_search(board_t * board, int alpha, int beta, int depth, int height, mv_t pv[], int node_type) {
static int full_search(Position* board, int alpha, int beta, int depth, int height, Move pv[], int node_type) {
   bool in_check;
   bool single_reply;
   int trans_move, trans_depth, trans_min_depth, trans_max_depth, trans_min_value, trans_max_value;
   int min_value, max_value;
   int old_alpha;
   int value, best_value;
   int move, best_move;
   int new_depth;
   int played_nb;
   int i;
   int opt_value;
   bool reduced;
   
   attack_t attack[1];
   sort_t sort[1];
   undo_t undo[1];
   mv_t new_pv[HeightMax];
   mv_t played[256];

   ASSERT(board!=NULL);
   ASSERT(range_is_ok(alpha,beta));
   ASSERT(depth_is_ok(depth));
   ASSERT(height_is_ok(height));
   ASSERT(pv!=NULL);
   ASSERT(node_type==NodePV||node_type==NodeCut||node_type==NodeAll);

   ASSERT(board_is_legal(board));

   // horizon?

   if (depth <= 0) return full_quiescence(board,alpha,beta,0,height,pv);

   // init

   SearchCurrent->node_nb++;
   SearchInfo->check_nb--;
   PV_CLEAR(pv);

   if (height > SearchCurrent->max_depth) SearchCurrent->max_depth = height;

   if (SearchInfo->check_nb <= 0) {
      SearchInfo->check_nb += SearchInfo->check_inc;
      search_check();
   }

   // draw?

   if (board_is_repetition(board) || recog_draw(board)) return ValueDraw;

   // mate-distance pruning

   if (UseDistancePruning) {

      // lower bound

      value = VALUE_MATE(height+2); // does not work if the current position is mate
      if (value > alpha && board_is_mate(board)) value = VALUE_MATE(height);

      if (value > alpha) {
         alpha = value;
         if (value >= beta) return value;
      }

      // upper bound

      value = -VALUE_MATE(height+1);

      if (value < beta) {
         beta = value;
         if (value <= alpha) return value;
      }
   }

   // transposition table

   trans_move = MoveNone;

   if (UseTrans && depth >= TransDepth) {

      if (trans_retrieve(Trans,board->key,&trans_move,&trans_min_depth,&trans_max_depth,&trans_min_value,&trans_max_value)) {

         // trans_move is now updated

         if (node_type != NodePV) {

            if (UseMateValues) {

               if (trans_min_value > +ValueEvalInf && trans_min_depth < depth) {
                  trans_min_depth = depth;
               }

               if (trans_max_value < -ValueEvalInf && trans_max_depth < depth) {
                  trans_max_depth = depth;
               }
            }

            min_value = -ValueInf;

            if (DEPTH_MATCH(trans_min_depth,depth)) {
               min_value = value_from_trans(trans_min_value,height);
               if (min_value >= beta) return min_value;
            }

            max_value = +ValueInf;

            if (DEPTH_MATCH(trans_max_depth,depth)) {
               max_value = value_from_trans(trans_max_value,height);
               if (max_value <= alpha) return max_value;
            }

            if (min_value == max_value) return min_value; // exact match
         }
      }
   }

   // height limit

   if (height >= HeightMax-1) return eval(board);

   // more init

   old_alpha = alpha;
   best_value = ValueNone;
   best_move = MoveNone;
   played_nb = 0;

   attack_set(attack,board);
   in_check = ATTACK_IN_CHECK(attack);

   // null-move pruning

   if (UseNull && depth >= NullDepth && node_type != NodePV) {

      if (!in_check
       && !value_is_mate(beta)
       && do_null(board)
       && (!UseNullEval || depth <= NullReduction+1 || eval(board) >= beta)) {

         // null-move search

         new_depth = depth - NullReduction - 1;

         move_do_null(board,undo);
         value = -full_search(board,-beta,-beta+1,new_depth,height+1,new_pv,NODE_OPP(node_type));
         move_undo_null(board,undo);

         // verification search

         if (UseVer && depth > VerReduction) {

            if (value >= beta && (!UseVerEndgame || do_ver(board))) {

               new_depth = depth - VerReduction;
               ASSERT(new_depth>0);

               value = full_no_null(board,alpha,beta,new_depth,height,new_pv,NodeCut,trans_move,&move);

               if (value >= beta) {
                  ASSERT(move==new_pv[0]);
                  played[played_nb++] = move;
                  best_move = move;
                  best_value = value;
                  pv_copy(pv,new_pv);
                  goto cut;
               }
            }
         }

         // pruning

         if (value >= beta) {

            if (value > +ValueEvalInf) value = +ValueEvalInf; // do not return unproven mates
            ASSERT(!value_is_mate(value));

            // pv_cat(pv,new_pv,MoveNull);

            best_move = MoveNone;
            best_value = value;
            goto cut;
         }
      }
   }

   // Internal Iterative Deepening

   if (UseIID && depth >= IIDDepth && node_type == NodePV && trans_move == MoveNone) {

      new_depth = depth - IIDReduction;
      ASSERT(new_depth>0);

      value = full_search(board,alpha,beta,new_depth,height,new_pv,node_type);
      if (value <= alpha) value = full_search(board,-ValueInf,beta,new_depth,height,new_pv,node_type);

      trans_move = new_pv[0];
   }

   // move generation

   sort_init(sort,board,attack,depth,height,trans_move);

   single_reply = false;
   if (in_check && LIST_SIZE(sort->list) == 1) single_reply = true; // HACK

   // move loop

   opt_value = +ValueInf;

   while ((move=sort_next(sort)) != MoveNone) {

      // extensions

      new_depth = full_new_depth(depth,move,board,single_reply,node_type==NodePV);

      // history pruning

      reduced = false;

      if (UseHistory && depth >= HistoryDepth && node_type != NodePV) {
         if (!in_check && played_nb >= HistoryMoveNb && new_depth < depth) {
            ASSERT(best_value!=ValueNone);
            ASSERT(played_nb>0);
            ASSERT(sort->pos>0&&move==LIST_MOVE(sort->list,sort->pos-1));
            value = sort->value; // history score
            if (value < HistoryValue) {
               ASSERT(value>=0&&value<16384);
               ASSERT(move!=trans_move);
               ASSERT(!move_is_tactical(move,board));
               ASSERT(!move_is_check(move,board));
               new_depth--;
               reduced = true;
            }
         }
      }

      // futility pruning

      if (UseFutility && depth == 1 && node_type != NodePV) {

         if (!in_check && new_depth == 0 && !move_is_tactical(move,board) && !move_is_dangerous(move,board)) {

            ASSERT(!move_is_check(move,board));

            // optimistic evaluation

            if (opt_value == +ValueInf) {
               opt_value = eval(board) + FutilityMargin;
               ASSERT(opt_value<+ValueInf);
            }

            value = opt_value;

            // pruning

            if (value <= alpha) {

               if (value > best_value) {
                  best_value = value;
                  PV_CLEAR(pv);
               }

               continue;
            }
         }
      }

      // recursive search

      move_do(board,move,undo);

      if (node_type != NodePV || best_value == ValueNone) { // first move
         value = -full_search(board,-beta,-alpha,new_depth,height+1,new_pv,NODE_OPP(node_type));
      } else { // other moves
         value = -full_search(board,-alpha-1,-alpha,new_depth,height+1,new_pv,NodeCut);
         if (value > alpha) { // && value < beta
            value = -full_search(board,-beta,-alpha,new_depth,height+1,new_pv,NodePV);
         }
      }

      // history-pruning re-search

      if (HistoryReSearch && reduced && value >= beta) {

         ASSERT(node_type!=NodePV);

         new_depth++;
         ASSERT(new_depth==depth-1);

         value = -full_search(board,-beta,-alpha,new_depth,height+1,new_pv,NODE_OPP(node_type));
      }

      move_undo(board,move,undo);

      played[played_nb++] = move;

      if (value > best_value) {
         best_value = value;
         pv_cat(pv,new_pv,move);
         if (value > alpha) {
            alpha = value;
            best_move = move;
            if (value >= beta) goto cut;
         }
      }

      if (node_type == NodeCut) node_type = NodeAll;
   }

   // ALL node

   if (best_value == ValueNone) { // no legal move
      if (in_check) {
         ASSERT(board_is_mate(board));
         return VALUE_MATE(height);
      } else {
         ASSERT(board_is_stalemate(board));
         return ValueDraw;
      }
   }

cut:

   ASSERT(value_is_ok(best_value));

   // move ordering

   if (best_move != MoveNone) {

      good_move(best_move,board,depth,height);

      if (best_value >= beta && !move_is_tactical(best_move,board)) {

         //ASSERT(played_nb>0&&played[played_nb-1]==best_move);

         for (i = 0; i < played_nb-1; i++) {
            move = played[i];
            ASSERT(move!=best_move);
            history_bad(move,board);
         }

         history_good(best_move,board);
      }
   }

   // transposition table
   /*
   if (UseTrans && depth >= TransDepth) {

      trans_move = best_move;
      trans_depth = depth;
      trans_min_value = (best_value > old_alpha) ? value_to_trans(best_value,height) : -ValueInf;
      trans_max_value = (best_value < beta)      ? value_to_trans(best_value,height) : +ValueInf;

      trans_store(Trans,board->key,trans_move,trans_depth,trans_min_value,trans_max_value);
   }
   
   return best_value;
}

*/






/////////////////////////////////////////////////////////////////
// Knut initial AlphaBeta
/////////////////////////////////////////////////////////////////

//integer procedure F2(position p, integer alpha, integer beta):
//	begin integer m,i,t,d;
//		determine the successor positions p1..pd;
//		if d=0 then F2:=f(p) else
//		begin m:=alpha;
//			for i:=l step 1 until d do
//				begin t:= -F2(Pi, -beta, -m);
//					if t>m the m:=t;
//					if m>= beta then goto done;
//				end
//			done: F2:=m;
//		end
//	end


/////////////////////////////////////////////////////////////////
// Knut iterative AlphaBeta
/////////////////////////////////////////////////////////////////

//integer procedure alphabeta(ref (position) p)
//	begin integer l; // level of recursion
//		integer array a[-2;L]; // stack for recursion where a[l-2], a[l-1],a[l],a[l+1] denote respectively alpha, -beta, m, -t in procedure F2
//		ref(position) array r[0;L+1]; //another stack for recursion, where r[l] and r[l+1] denote respectively p and q in F2
//		l:=0;a[-2]:=a[-1]:=-oo; r[0]:=p;
//	F2: generate(r[l]);
//		r[l+1]:=first(r[l]);
//		if r[l+1]=V then a[l]:=f(r[l]) else
//		begin a[l]:=a[l-2];
//			loop: l:=l+1;goto F2;
//			resume: if -a[l+1] > a[l] then
//				begin a[l] := -a[l+1];
//					if a[l+1] <= a[l-1] then go to done;
//				end;
//				r[l+1]:=next(r[l+1]);
//				if r[l+1]!=V then goto loop;
//		end
//	done: l:= l-1; if l>= 0 then goto resume;
//	alphabeta:=a[0]
//end
//
// L = stack size
//#define AOFFSET 2
//#define L 254
//// C++ implementation
//int alphabeta(Position* p){
//	int l;
//	int a[L+AOFFSET];
//	Position* r[L+1];
//	l=0;a[-2+AOFFSET]=a[-1+AOFFSET]=-VALUE_INFINITE; r[0]=p;
//	
//	list<Move> legalMoves;
//	GetLegalMoves(p,legalMoves);
//F2:
//	p->Play(legalMoves[l]);
//	r[l+1]=new Position(p);
//	if(r[l+1]== V??) a[l+AOFFSET]=f(r[l]) // V == leave ??
//	else
//	for(a[l+AOFFSET]:=a[l-2+AOFFSET];r[l+1]!=V;l++){
//
//	}
//
//
//	
//
//
//}

